﻿using AutoMapper;
using ERPSystem.Common.Domains.PurchaseInvoiceCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using SqlSugar;

namespace SalesManagementWrite.API.SalesManagementWrites.PurchaseReturnOrderes
{
    public class PurchaseReturnOrderUpdateHandler:IRequestHandler<PurchaseReturnOrderUpdateCommand,Result>
    {
        private readonly IBaseRepository<PurchaseReturnOrder> _purchaseReturnOrderRepository;
        private readonly IBaseRepository<PurchaseReturnOrderSubtable> _purchaseReturnOrderSubtableRepository;
        private readonly IMapper _mapper;
        private readonly ISqlSugarClient _sqlSugarClient;

        public PurchaseReturnOrderUpdateHandler(IBaseRepository<PurchaseReturnOrder> purchaseReturnOrderRepository, IBaseRepository<PurchaseReturnOrderSubtable> purchaseReturnOrderSubtableRepository, IMapper mapper, ISqlSugarClient sqlSugarClient)
        {
            _purchaseReturnOrderRepository = purchaseReturnOrderRepository;
            _purchaseReturnOrderSubtableRepository = purchaseReturnOrderSubtableRepository;
            _mapper = mapper;
            _sqlSugarClient = sqlSugarClient;
        }


        /// <summary>
        /// 修改采购退货单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PurchaseReturnOrderUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            _sqlSugarClient.Ado.BeginTran();
            try
            {
                var purchaseReturnOrder  =await(await _purchaseReturnOrderRepository.GetAll()).FirstAsync(c=>c.PurchaseReturnOrderNo==request.PurchaseReturnOrderNo);
                var purchaseReturnOrderRes = await _purchaseReturnOrderRepository.Update(purchaseReturnOrder);
                List<PurchaseReturnOrderSubtable> purchaseReturnOrderSubtable = new List<PurchaseReturnOrderSubtable>();
                purchaseReturnOrderSubtable = await (await _purchaseReturnOrderSubtableRepository.GetAll()).Where(c => c.PurchaseReturnOrderSerialNumber == request.PurchaseReturnOrderSerialNumber).ToListAsync();
               var purchaseReturnOrderSubtableRes = await _purchaseReturnOrderSubtableRepository.UpdateRange(purchaseReturnOrderSubtable);
                if (purchaseReturnOrderRes > 0 && purchaseReturnOrderSubtableRes > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "修改成功";
                }
                _sqlSugarClient.Ado.CommitTran();
                return result;
            }
            catch (Exception ex)
            {

                _sqlSugarClient.Ado.RollbackTran();
                throw ex;
            }
        }
    }
}
